package com.metaera.app.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lxj.xpopup.XPopup;
import com.metaera.app.Constants;
import com.metaera.app.R;
import com.metaera.app.controller.presenter.ArticleDetailsPresenter;
import com.metaera.app.controller.presenter.ArticleRecommendPresenter;
import com.metaera.app.controller.presenter.FollowAuthorPresenter;
import com.metaera.app.controller.presenter.LikeInformationPresenter;
import com.metaera.app.controller.view.BasicNetworkRequestView;
import com.metaera.app.controller.view.FollowAuthorView;
import com.metaera.app.controller.view.core.INetworkRequestView;
import com.metaera.app.data.model.InformationDetailsResponse;
import com.metaera.app.data.network.ApiParam;
import com.metaera.app.ui.adapters.ArticleRecommendAdapter;
import com.metaera.app.ui.adapters.LabelAdapter;
import com.metaera.app.ui.core.BaseRequestActivity;
import com.metaera.app.ui.popup.SharePopup;
import com.metaera.app.utils.DateTime;
import com.metaera.app.utils.LoginClickListener;
import com.metaera.app.utils.ShareClickListener;
import com.metaera.app.utils.ViewUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 文章详情
 */
public class ArticleDetailsActivity extends BaseRequestActivity {

    public static Intent newInstance(Context context, int id) {
        Intent intent = new Intent(context, ArticleDetailsActivity.class);
        intent.putExtra(Constants.ARTICLE_ID, id);
        return intent;
    }

    private WebView mWebView;


    @Override
    protected int getContentLayoutId() {

        return R.layout.activity_quick_detail_test;
    }

    @Override
    protected void initialize(Bundle savedInstanceState) {
        ViewUtils.addStatusBarHeightPadding(findViewById(R.id.layout_container));

        // find
        mWebView = findViewById(R.id.web_view);
        View layoutRecommend = findViewById(R.id.layout_recommend);
        RecyclerView recycleRecommend = findViewById(R.id.recycle_recommend);

        // init view
        mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.getSettings().setSupportZoom(false);

//        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recycleRecommend.getContext(), DividerItemDecoration.VERTICAL);
//        Drawable drawable = ContextCompat.getDrawable(recycleRecommend.getContext(), R.drawable.shape_item_divider);
//        dividerItemDecoration.setDrawable(drawable);
//        recycleRecommend.addItemDecoration(dividerItemDecoration);

        // network
        int articleId = getIntent().getIntExtra(Constants.ARTICLE_ID, 0);
        ArticleDetailsPresenter presenter = new ArticleDetailsPresenter();
        presenter.setModelAndView(this::renderArticle);
        presenter.execute(articleId);

        ArticleRecommendPresenter recommendPresenter = new ArticleRecommendPresenter();
        recommendPresenter.setModelAndView(data -> {
            layoutRecommend.setVisibility(data.isEmpty() ? View.GONE : View.VISIBLE);
            recycleRecommend.setAdapter(new ArticleRecommendAdapter(data));
        });
        recommendPresenter.execute(articleId);

        // listener
        findViewById(R.id.iv_arrow_back).setOnClickListener(v -> finish());
    }

    private void renderArticle(InformationDetailsResponse data) {
        TextView tvDate = findViewById(R.id.tv_date);
        TextView tvTitle = findViewById(R.id.tv_title);
        TextView tvAuthor = findViewById(R.id.tv_author);
        TextView buttonFollow = findViewById(R.id.button_follow);
        RecyclerView labelRecyclerView = findViewById(R.id.label_recycler_view);
        View layout_choice = findViewById(R.id.layout_choice);
        ImageView ivLike = findViewById(R.id.iv_like);
        ImageView ivFavorite = findViewById(R.id.iv_favorite);
        TextView tvLikeNumber = findViewById(R.id.tv_like_number);

        ivLike.setSelected(data.getIs_like() == 1);
        ivFavorite.setSelected(data.getIs_collection() == 1);
        tvLikeNumber.setText(String.valueOf(data.getLike_num()));

        tvTitle.setText(data.getTitle());
        tvDate.setText(DateTime.format(new Date(data.getRelease_time_stamp() * 1000L)));
        tvAuthor.setText(data.getAuthor().getNickname());
        buttonFollow.setSelected(data.getIs_follow() == ApiParam.FOLLOW_AUTHOR);
        buttonFollow.setText(buttonFollow.isSelected() ? R.string.followed : R.string.follow);

        InformationDetailsResponse.SpecialInfo special = data.getSpecial_info();
        if (special != null) {
            TextView tv_choice_title = layout_choice.findViewById(R.id.tv_choice_title);
            layout_choice.setVisibility(View.VISIBLE);
            tv_choice_title.setText("▪ " + special.getName());
            layout_choice.setOnClickListener(v ->
                    startActivity(ChoiceTopicDetailsActivity.newInstance(v.getContext(), special.getId())));
        }

        tvAuthor.setOnClickListener(v -> // 个人主页
                startActivity(UserProfileActivity.newIntent(this, data.getAuthor_id())));

        buttonFollow.setOnClickListener(new LoginClickListener(v -> {
            FollowAuthorPresenter presenter = new FollowAuthorPresenter();
            presenter.setModelAndView(new BasicNetworkRequestView<>(new FollowAuthorView(buttonFollow)));
            presenter.follow(data.getAuthor_id(), !v.isSelected());
        }));

        // 点赞
        ivLike.setOnClickListener(new LoginClickListener(v -> {
            LikeInformationPresenter presenter = new LikeInformationPresenter();
            presenter.setModelAndView(_d -> {
                ivLike.setSelected(!ivLike.isSelected());
                tvLikeNumber.setText(String.valueOf(data.getLikeNum(ivLike.isSelected())));
            });

            presenter.like(data.getId(), !ivLike.isSelected());
        }));

        ivFavorite.setOnClickListener(new LoginClickListener(v -> {
            LikeInformationPresenter presenter = new LikeInformationPresenter();
            presenter.setModelAndView(_d -> ivFavorite.setSelected(!ivFavorite.isSelected()));
            presenter.collection(data.getId(), !ivFavorite.isSelected());
        }));

//        String desc = data.getContent();
//        String description = (getChinese(desc).length() > 25 ? getChinese(desc).substring(0, 25) : desc) + "...";
        String description = data.getIllustrate();

        findViewById(R.id.iv_share).setOnClickListener(v ->
            new XPopup.Builder(v.getContext())
                    .asCustom(
                            new SharePopup(
                                    v.getContext(),
                                    data.getTitle(),
                                    description,
                                    ApiParam.LINK_SHARE_5 + data.getId(),
                                    R.mipmap.ic_launcher
                            )
                    )
                    .show()
        );

        findViewById(R.id.tv_wx).setOnClickListener(new ShareClickListener(
                SendMessageToWX.Req.WXSceneSession,
                data.getTitle(),
                description,
                ApiParam.LINK_SHARE_5 + data.getId(),
                R.mipmap.ic_launcher
        ));

        findViewById(R.id.tv_friend).setOnClickListener(new ShareClickListener(
                SendMessageToWX.Req.WXSceneTimeline,
                data.getTitle(),
                description,
                ApiParam.LINK_SHARE_5 + data.getId(),
                R.mipmap.ic_launcher
        ));

        labelRecyclerView.setAdapter(new LabelAdapter(data.getLabel_info())); // 标签

//        TextView text_view_test = findViewById(R.id.text_view_test);
//        text_view_test.setText(Html.fromHtml(data.getContent()));

        // html
        mWebView.loadData(getHtmlData(data.getContent()), "text/html", "UTF-8");
        mWebView.loadDataWithBaseURL(null, getHtmlData(data.getContent()), "text/html", "UTF-8", null);
    }


    private String getHtmlData(String bodyHTML) {
        String head = "<head>"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
                + "<style>img{max-width: 100%; width:100%; height:auto;}*{margin:0px;line-height:1.8;}</style>"
                + "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }




}
